//楼栋编辑
import * as React from 'react';
import {
  Form,
  Select,
  Input,
  Button,
  Col,
  Row,
  Checkbox,
  Tabs,
  DatePicker,
  Modal,
  Upload,Icon, notification ,Spin ,message
} from 'antd';
import axios from 'axios';
import Api from '../../services/apis';
import moment from 'moment';

import Link from 'umi/link';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './style.less';

const FormItem = Form.Item;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;
const TabPane = Tabs.TabPane;
const { TextArea } = Input;
const confirm = Modal.confirm;

@connect(({ user, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))

class HouseEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      step: '1',
      info: {},
      loading: false,
      fileList: [],
      previewVisible: false,
      previewImage: '',
      loading: false,
    };
  }

  componentWillMount() {
    const houseCode = this.props.location.query.houseCode;
    this.setState({
      houseCode: houseCode
    }, () => {
      this.getData();
    })
  }
  
  getData() {
    const that = this;
    
    that.setState({ loading: true });
    axios.get(Api.amQueryHouse, {
      params: {
        houseCode: that.state.houseCode
      }
    }).then(function (res) {
      const { data } = res;
      const dataImgs = data.imageData.concat(data.imageCode)
      const images = [];
      dataImgs.forEach((item, i) => {
        const splits = item.filePath.split('/');
        const name = splits[splits.length - 1];
        const img = {
          name: name,
          url: 'http://192.168.50.55:55555/res_file' + item.filePath,
          status: 'done',
          uid: i,
          imageId: item.imageId
        };
        images.push(img);
      })
      that.setState({
        info: data,
        fileList: images
      })

      that.props.form.setFieldsValue({
        houseCode: that.state.houseCode,
        location: data.location,
        unitNumber: data.unitNumber,
        currentFloor: data.currentFloor?String(data.currentFloor):'',
        houseName2: data.houseName2,
        houseProperty: data.houseProperty,
        houseAction: data.houseAction,
        buildingArea: data.buildingArea,
        useArea: data.useArea,
        houseManageDept: data.houseManageDept,
        houseDoorModel: data.houseDoorModel,
        houseToward: data.houseToward,
        houseDecorate: data.houseDecorate,
        x: data.x,
        y: data.y,
        houseIsable: data.houseIsable,
        housevenuenumber: data.housevenuenumber,
        housevenuethigh: data.housevenuethigh,
        housevenuedancearea: data.housevenuedancearea,
        housevenuetypehx: data.housevenuetypehx,
        housevenuetypekz: data.housevenuetypekz,
        housevenuetypejy: data.housevenuetypejy,
        housevenueisnatural: data.housevenueisnatural=='1'?true:false,
        housevenueisled: data.housevenueisled=='1'?true:false,
        housevenueisprojector: data.housevenueisprojector=='1'?true:false,
        housevenueisvideo: data.housevenueisvideo=='1'?true:false,
        housevenueispillars: data.housevenueispillars=='1'?true:false,
        housevenueconfig: data.housevenueconfig,
        housevenuenote: data.housevenuenote,
      })
      
      that.setState({ loading: false });
    })
  }
  
  save() {
    const that = this;
    
    this.props.form.validateFields((err, values) => {
      if (!err) {
        that.setState({ loading: true });
        axios.post(Api.amModifyHouse, {
          houseCode: that.state.houseCode,
          location: values.location,
          buildingName: values.buildingName,
          unitNumber: values.unitNumber,
          currentFloor: values.currentFloor,
          houseName2: values.houseName2,
          houseProperty: values.houseProperty,
          houseAction: values.houseAction,
          buildingArea: values.buildingArea,
          useArea: values.useArea,
          houseManageDept: values.houseManageDept,
          houseDoorModel: values.houseDoorModel,
          houseToward: values.houseToward,
          houseDecorate: values.houseDecorate,
          x: values.x,
          y: values.y,
          houseIsable: values.houseIsable,
          housevenuenumber: values.housevenuenumber,
          housevenuethigh: values.housevenuethigh,
          housevenuedancearea: values.housevenuedancearea,
          housevenuetypehx: values.housevenuetypehx,
          housevenuetypekz: values.housevenuetypekz,
          housevenuetypejy: values.housevenuetypejy,
          housevenueisnatural: values.housevenueisnatural?'1':'0',
          housevenueisled: values.housevenueisled?'1':'0',
          housevenueisprojector: values.housevenueisprojector?'1':'0',
          housevenueisvideo: values.housevenueisvideo?'1':'0',
          housevenueispillars: values.housevenueispillars?'1':'0',
          housevenueconfig: values.housevenueconfig,
          housevenuenote: values.housevenuenote,
        }).then(function (res) {
          const { message } = res.data;
          notification.destroy();
          notification['success']({ message: message });
          that.setState({ loading: false });
          
          if (message == '保存成功') {
            window.close();
          }
        })
      }
    })
  }


  changeStep(stepType) {
    let step = parseInt(this.state.step);
    if (stepType == 'pre') {
      step = step - 1;
    } else {
      step = step + 1;
    }
    this.setState({
      step: String(step)
    });
  }
  cancelEdit(){
    confirm({
      title: '确定取消编辑？',
      content: '信息将不会保存。',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        window.close();
      }
    });
  }

  tabClick(step) {
    this.setState({
      step: String(step)
    });
  }
  
  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleChange(info) {
    const { fileList } = info;
    this.setState({ fileList, fileIds: fileList });
    if (fileList[fileList.length-1].status === 'done') {
      message.success(`${fileList[fileList.length-1].name} 图片上传成功！`);
    } else if (fileList[fileList.length-1].status === 'error') {
      message.error(`${fileList[fileList.length-1].name} 图片上传失败！`);
    }
  }
  
  removePic(info) {
    const that = this;
    let p = new Promise((resp, rej) => {

      if (!info.imageId) {
        message.error('新上传的图片没有imageId，请刷新后再删除！');
        rej('error');
        return;
      }
      axios.get(Api.amDeletePic, {
        params: {
          imageId : info.imageId
        }
      }).then((res) => {
        message.success(res.data.message);
        if (res.data.message === '删除成功！') {
          const index = that.state.fileList.indexOf(info);
          const newFileList = that.state.fileList.slice();
          newFileList.splice(index, 1);
          that.setState({fileList:newFileList})
          resp('success');
        } else {
          rej('error');
        };
      });
    });
    return p;
  }


  beforeUpload = (file) => {
    this.setState(state => ({
      fileList: [...state.fileList, file],
    }));
    return false;
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const {
      currentUserLoading,
    } = this.props;
    const plainOptions = ['Apple', 'Pear', 'Orange'];
    const data = this.state.info;
    const { previewVisible, previewImage, fileList } = this.state;
    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className='mainContainer'>
          <Form layout='inline' align='left' onSubmit={this.query}>
            <Spin spinning={this.state.loading}>
            <Tabs
              defaultActiveKey="1"
              activeKey={this.state.step}
              onTabClick={this.tabClick.bind(this)}
            >
              <TabPane tab="第一步 基本信息" key="1">
                <div className='contentHeader'>
                  <div className="contentHeaderTitle">
                    <p>基本信息</p>
                    <p>BASIC INFORMATION</p>
                  </div>
                </div>
                <Row>
                  <Col span={8}>
                    <FormItem label="所属单位：">
                      {data.transferUnit ? data.transferUnit  : '-'}
                    </FormItem>
                  </Col>
                  <Col span={16}>
                    <FormItem label="详细地址：">
                      {
                        getFieldDecorator('location', {
                          rules:[{required:true,messeage:'请输入详细地址！'}]
                        })(
                          <Input placeholder="请输入详细地址" />
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="栋号：">
                      {data.buildingName ? data.buildingName  : '-'}
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="单元号：">
                      {
                        getFieldDecorator('unitNumber')(
                          <Input placeholder="请输入单元号" />
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="楼层：">
                      {
                        getFieldDecorator('currentFloor', {
                          rules: [{ required: true, messeage: '请输入楼层！' },
                          ]
                        })(
                          <Input placeholder="请输入楼栋名称" />
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="房号：">
                      {
                        getFieldDecorator('houseName2', {
                          rules:[{required:true,messeage:'请输入房号！'}]
                        })(
                          <Input placeholder="请输入房号" />
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="住房性质：">
                      {getFieldDecorator('houseProperty')(
                      <Select placeholder="请选择住房用途">
                        <Option value="01">自用</Option>
                        <Option value="02">出租</Option>
                      </Select>)}
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="住房用途：">
                      {getFieldDecorator('houseAction')(
                      <Select placeholder="请选择住房性质">
                        <Option value="01">设备间</Option>
                        <Option value="02">管线</Option>
                        <Option value="03">配电室</Option>
                        <Option value="04">新风机房</Option>
                        <Option value="05">空调机房</Option>
                        <Option value="06">洗消间</Option>
                        <Option value="07">酒店客房</Option>
                        <Option value="08">卫生间（男）</Option>
                        <Option value="09">卫生间（女）</Option>
                        <Option value="10">强电间</Option>
                        <Option value="11">弱电间</Option>
                        <Option value="12">台球室</Option>
                        <Option value="13">影音室</Option>
                        <Option value="14">开水间</Option>
                        <Option value="15">贵宾室</Option>
                        <Option value="16">资料室</Option>
                        <Option value="17">服务间</Option>
                        <Option value="18">男淋浴室</Option>
                        <Option value="19">女淋浴室</Option>
                        <Option value="20">会议室</Option>
                        <Option value="21">报告厅</Option>
                        <Option value="22">音控室</Option>
                        <Option value="23">阅览室</Option>
                        <Option value="24">兵乓球室</Option>
                        <Option value="25">冷库</Option>
                        <Option value="26">监控室</Option>
                        <Option value="27">网络机房</Option>
                        <Option value="28">办公室</Option>
                        <Option value="29">厨房</Option>
                        <Option value="30">超市</Option>
                        <Option value="31">洗衣室</Option>
                        <Option value="32">理发室</Option>
                        <Option value="33">更衣间</Option>
                        <Option value="34">取款机单独间</Option>
                        <Option value="35">库房</Option>
                        <Option value="36">餐厅</Option>
                        <Option value="37">包房</Option>
                        <Option value="38">电梯厅</Option>
                        <Option value="39">电梯</Option>
                        <Option value="40">门厅</Option>
                        <Option value="41">楼梯</Option>
                        <Option value="42">卫生间</Option>
                        <Option value="43">活动室</Option>
                        <Option value="44">多功能厅</Option>
                      </Select>)}
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="建筑面积（㎡）：">
                      {
                        getFieldDecorator('buildingArea')(
                          <Input placeholder="请输入建筑面积" />
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="使用面积（㎡）：">
                      {
                        getFieldDecorator('useArea')(
                          <Input placeholder="请输入使用面积" />
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="住房管理(售房)单位：">
                      {
                        getFieldDecorator('houseManageDept')(
                          <Input placeholder="请填写住房管理(售房)单位"/>
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="户型：">
                      {
                        getFieldDecorator('houseDoorModel')(
                          <Input placeholder="请填写户型"/>
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="朝向：">
                      {
                        getFieldDecorator('houseToward')(
                          <Input placeholder="请填写朝向"/>
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="装修：">
                      {
                        getFieldDecorator('houseDecorate')(
                          <Input placeholder="请填写装修"/>
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="横坐标：">
                      {
                        getFieldDecorator('x')(
                          <Input placeholder="请填写横坐标"/>
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="纵坐标：">
                      {
                        getFieldDecorator('y')(
                          <Input placeholder="请填写纵坐标"/>
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="房间是否可用：">
                      {
                        getFieldDecorator('houseIsable')(
                          <Select placeholder="请选择质量等级">
                            <Option value="1">可用</Option>
                            <Option value="2">不可用</Option>
                          </Select>)}
                    </FormItem>
                  </Col>
                  </Row>
                {
                  [20, 15, 21, 28, 36].indexOf(parseInt(data.houseAction)) > -1 ?
                  <div>
                    <div className='contentHeader'>
                      <div className="contentHeaderTitle">
                        <p>会场信息</p>
                        <p>MEETING INFORMATION</p>
                      </div>
                    </div>
                    <Row>
                      <Col span={8}>
                        <FormItem label="会场编号/名称：">
                          {
                            getFieldDecorator('housevenuenumber')(
                              <Input placeholder="请输入会场编号/名称" />
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="会场挑高：">
                          {
                            getFieldDecorator('housevenuethigh')(
                              <Input placeholder="请输入会场挑高" />
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="舞台面积：">
                          {
                            getFieldDecorator('housevenuedancearea')(
                              <Input placeholder="请输入舞台面积" />
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="容纳人数(回形)：">
                          {
                            getFieldDecorator('housevenuetypehx')(
                              <Input placeholder="请输入容纳人数(回形)" />
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="容纳人数(课桌)：">
                          {
                            getFieldDecorator('housevenuetypekz')(
                              <Input placeholder="请输入容纳人数(课桌)" />
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="容纳人数(剧院)：">
                          {
                            getFieldDecorator('housevenuetypejy')(
                              <Input placeholder="请输入容纳人数(剧院)" />
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="是否自然光：">
                          {
                            getFieldDecorator('housevenueisnatural', {
                              valuePropName: 'checked',
                            })(
                              <Checkbox></Checkbox>
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="是否有LED：">
                          {
                            getFieldDecorator('housevenueisled', {
                              valuePropName: 'checked',
                            })(
                              <Checkbox></Checkbox>
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="是否有投影仪：">
                          {
                            getFieldDecorator('housevenueisprojector', {
                              valuePropName: 'checked',
                            })(
                              <Checkbox></Checkbox>
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="是否有显示器：">
                          {
                            getFieldDecorator('housevenueisvideo', {
                              valuePropName: 'checked',
                            })(
                              <Checkbox></Checkbox>
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="是否有柱子：">
                          {
                            getFieldDecorator('housevenueispillars', {
                              valuePropName: 'checked',
                            })(
                              <Checkbox></Checkbox>
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={24}>
                        <FormItem label="会场配置：">
                          {
                            getFieldDecorator('housevenueconfig')(
                              <Input.TextArea placeholder="请输入会场配置" style={{width:'985px'}} />
                            )
                          }
                        </FormItem>
                      </Col>
                      <Col span={24}>
                        <FormItem label="备注说明：">
                          {
                            getFieldDecorator('housevenuenote')(
                              <Input.TextArea placeholder="请输入会场配置" style={{width:'985px'}} />
                            )
                          }
                        </FormItem>
                      </Col>
                    </Row>   
                  </div>
                  :null
                }
              </TabPane>

              <TabPane tab="第二步 照片" key='2'>
                <div className='contentHeader'>
                  <div className="contentHeaderTitle">
                    <p>照片</p>
                    <p></p>
                  </div>
                </div>
                <Row>
                  <div className="clearfix">
                    <Upload
                      action={`${Api.amUploadPic}?addressId=${this.state.houseCode}`}
                      listType="picture-card"
                      fileList={this.state.fileList}
                      onPreview={this.handlePreview.bind(this)}
                      onChange={this.handleChange.bind(this)}
                      onRemove={this.removePic.bind(this)}
                    >
                      <div>
                        <Icon type="plus" />
                        <div className="ant-upload-text">上传</div>
                      </div>
                    </Upload>
                    <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                      <img alt="example" style={{ width: '100%' }} src={previewImage} />
                    </Modal>
                  </div>
                </Row>
              </TabPane>
            </Tabs>
            </Spin>
            <div className={styles.energyEditFooter}>
              <Button type='primary' disabled={this.state.step === '1' ? true : false} onClick={()=>this.changeStep('pre')}>上一步</Button>
              &emsp;
              <Button type='primary' disabled={this.state.step !== '1' && this.state.step === '2' ? true : false} onClick={()=>this.changeStep('next')}>下一步</Button>
              &emsp;
              <Button type='primary' onClick={this.save.bind(this)}>保存</Button>
              &emsp;
              <Button type='primary' onClick={this.cancelEdit.bind(this)}>取消</Button>
            </div>
          </Form>
        </div>
      </PageHeaderWrapper >
    );
  }
}

const WrappedApp = Form.create()(HouseEdit);

export default WrappedApp;
